{% extends 'base.html' %}

{% block javascript %}

<script>

  function createDeviceEvent(event_name, event_id) {
     /* Creates peripheral event. */
     console.log("Creating device event: " + event_name)

     // Get function parameters
     if (event_id != null) {
      base_name = "#" + event_id;
      var value = $(base_name).val();
     }
     else {
      var value = null;
    }
     
     // Create recipient and request dicts
     recipient =  {
         "type": "Device",
         "name": null};
     request = {
         "type": event_name,
         "value": value};

      console.log(request)

     // Send create event request to endpoint
     $.ajax({
         url: "/api/event/",
         type: "POST",
         data: {
           "csrfmiddlewaretoken": "{{ csrf_token }}",
           "recipient": JSON.stringify(recipient),
           "request": JSON.stringify(request)
         },
         dataType: 'json',
         success: function(data) {
           console.log("Event request succeeded")

           // Get response message
           message = data.message
           alert(message);
           location.reload();
         },
         error: function(data) {
           console.log("Event request failed")

           // Get response message
           response_dict = JSON.parse(data.responseText)
           message = response_dict["message"]
           alert(message);
         }
     }); 
  }

   function startRecipe() {
      /* Starts a recipe. */
      console.log("Starting recipe")
      var uuid = $("#recipe_uuid").val()
      const startTime = document.getElementById('id_start_time');
      var date = undefined;
      if (startTime != undefined) {
        date = startTime.value
      }
      console.log('startRecipe uuid='+uuid);
      console.log('startRecipe date='+date);

      if( date ){
        var d = new Date(date)
        var timestamp = d.getTime() / 1000
      } else {
        var timestamp = null;
      }

      console.log('startRecipe timestamp='+timestamp)
      
      // Send create event request to endpoint
      $.ajax({
          url: "/api/recipe/" + uuid + "/start/",
          type: "POST",
          data: {
            "csrfmiddlewaretoken": "{{ csrf_token }}",
            "timestamp": timestamp
          },
          dataType: 'json',
          success: function(data) {
            console.log("Event request succeeded")
            message = data["message"]
            alert(message);
            location.reload();
          },
          error: function(data) {
            console.log("Event request failed")
            var dataDict = JSON.parse(data.responseText);
            var message = dataDict["message"];
            alert(message);
          }
      }); 
   }


   function stopRecipe() {
      /* Stops a recipe. */
      console.log("Stopping recipe")

      // Send stop request to endpoint
      $.ajax({
          url: "/api/recipe/stop/",
          type: "POST",
          data: {
            "csrfmiddlewaretoken": "{{ csrf_token }}"
          },
          dataType: 'json',
          success: function(data) {
            console.log("Stop recipe succeeded")
            message = data["message"]
            alert(message);
            location.reload();
          },
          error: function(data) {
            console.log("Stop recipe failed")
            var dataDict = JSON.parse(data.responseText);
            var message = dataDict["message"];
            alert(message);
          }
      }); 
   }

   function createRecipe() {
      /* Creates a recipe. */
      console.log("Creating recipe")

      // Get recipe json
      var recipe_json = $("#recipe_json").val();

      // Send stop request to endpoint
      $.ajax({
          url: "/api/recipe/",
          type: "POST",
          data: {
            "csrfmiddlewaretoken": "{{ csrf_token }}",
            "json": recipe_json
          },
          dataType: 'json',
          success: function(data) {
            console.log("Create recipe succeeded")
            message = data["message"]
            alert(message);
            location.reload();
          },
          error: function(data) {
            console.log("Create recipe failed")
            var dataDict = JSON.parse(data.responseText);
            var message = dataDict["message"];
            alert(message);
          }
      }); 
   }
   
</script>
{% endblock %}

{% block content %}

{% csrf_token %}

<head>
    <!-- https://code.jquery.com/jquery-3.2.1.min.js -->
    {% if network_is_connected %}
      <script crossorigin="anonymous" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f" src="/app/static/js/jquery.js"></script>
      {{ datetime_form.media }}
    {% endif %}
</head>

<body>
<div class="dashboard">
   <div class="row">
      <div class="col-sm">
         
            <h2> Recipe </h2>
            <div class="card">
            <p>
               <b>Mode:</b> {{ recipe_mode }} </br>   
               <b>Name:</b> {{ recipe_name }} </br>
               <b>UUID:</b> {{ recipe_uuid }} </br>
               <b>Started:</b> {{ recipe_start_datestring }} </br>
               <b>Progress:</b> {{ recipe_percent_complete_string }} </br>
               <b>Time Elapsed:</b> {{ recipe_time_elapsed_string }} </br>
               <b>Time Remaining:</b> {{ recipe_time_remaining_string }} </br>
               <b>Current Phase:</b> {{ recipe_current_phase }} </br>
               <b>Current Cycle:</b> {{ recipe_current_cycle }} </br>
               <b>Current Environment:</b> {{ recipe_current_environment_name }}
            </p>
            <p>
               <input type="text" id="recipe_json" name="recipe_json" placeholder='Paste recipe json here' required>
               <button class="btn" type="button" onClick="createRecipe()"><i class="icon-share"></i> Upload Recipe </button>
            </p>
            {% if recipe_uuid == None %}
            <select id="recipe_uuid">
              {% for recipe in recipes %}
                {% if recipe.uuid == selected_recipe.uuid %}
                  <option value="{{recipe.uuid}}" selected="selected"> Recipe: {{recipe.name}} </option>
                {% else %}
                  <option value="{{recipe.uuid}}"> Recipe: {{recipe.name}} </option>
                {% endif %}
              {% endfor %}
            </select>

            <!-- Datetime picker, only avaliable if we have a valid internet connection -->
              {% if network_is_connected %}
                {{ datetime_form.as_p }}
              {% endif %}
            <button class="btn" type="button" onClick="startRecipe()"><i class="icon-share"></i> Start Recipe </button>

            {% else %}
            <button class="btn" type="button" onClick="stopRecipe()"><i class="icon-share"></i> Stop Recipe </button>

            {% endif %}
         </div>
      </div>
      <div class="col-sm">
            <h2> Mode </h2>
            <div class="card">
            <p>
               {% for key, value in manager_modes.items %}
               <b>{{ key }}:</b> {{ value }} </br>
               {% endfor %}
            </p>
          </div>
            <h2> Health </h2>
            <div class="card">
            <p>
               {% for key, value in manager_healths.items %}
               <b>{{ key }}:</b> {{ value }} %</br>
               {% endfor %}
            </p>
         </div>
      </div>
      <div class="col-sm">
        
           <h2> Sensor </h2>
           <div class="card">
           <p>
              {% for key, value in current_environment.sensor_summary.items %}
              <b>{{ key }}:</b> {{ value }} </br>
              {% endfor %}
           </p>
         </div>
           <h2> Actuator </h2>
           <div class="card">
           <p>
              {% for key, value in current_environment.actuator_summary.items %}
              <b>{{ key }}:</b> {{ value }} </br>
              {% endfor %}
           </p>
         </div>
      </div>
   </div>
</div>
</body>
{% endblock %}
